﻿using System;
using System.Collections.Generic;
using System.Text;

using Codice.Utils;

using Redmine.Net.Api;
using Redmine.Net.Api.Types;

using Codice.Client.Extension.Types;

namespace Codice.Client.Extension
{
    class RedmineTestConnection : ITestConnection
    {
        private static string[] AUTH_EXCEPTION =
            new string[]{"Authorization Required",
                         "Unauthorized",
                         "Timeout",
                         "The operation has timed-out.",
                         "The underlying connection was closed: " +
                         "Unable to connect to the remote server."};

        private static readonly string SampleId = "1";

        // tests the connection to the server        
        public void TestConnection(BaseExtensionConfiguration config)
        {
            RedmineExtensionConfiguration redmineConfig = config as RedmineExtensionConfiguration;


            var manager = CreateRedmineManager(redmineConfig);

            Exception ex = null;
            int MAX_TEST_CONNECTION_RETRIES = 100;
            int retries = 0;
            do
            {
                try
                {
                    var issue1 = manager.GetObject<Issue>(SampleId, null);
                    return;
                }
                catch (Exception e)
                {
                    //Throw all exceptions except "Unexpected error receiving"
                    if (!(e is System.Net.WebException))
                    {
                        throw e;
                    }

                    foreach (string msg in AUTH_EXCEPTION)
                    {
                        if (e.Message.ToLower().IndexOf(msg.ToLower()) != -1)
                        {
                            throw e;
                        }
                    }
                    ex = e;

                }
            } while (retries < MAX_TEST_CONNECTION_RETRIES);

            throw ex;
        }

        private static RedmineManager CreateRedmineManager(RedmineExtensionConfiguration config)
        {
            string host = config.Url;
            string apikey = config.ApiKey;
            if (apikey == null || apikey == String.Empty)
            {
                string user = config.User;
                string password = CryptoServices.GetDecryptedPassword(config.Password);
            
                return new RedmineManager(host, user, password);
            }

            return new RedmineManager(host, apikey);
        }
    }
}
